/**
 * Copyright (c) 2024 小明IO
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Commercial use of this software requires prior written authorization from the Licensor.
 * 请注意：将 ESP-AI 代码用于商业用途需要事先获得许可方的授权。
 * 删除与修改版权属于侵权行为，请尊重作者版权，避免产生不必要的纠纷。
 *
 * @author 小明IO
 * @email  1746809408@qq.com
 * @github https://github.com/wangzongming/esp-ai
 * @websit https://espai.fun
 */

#include "main.h"

void ESP_AI::set_config()
{
    String wifi_name = server.arg("wifi_name");
    String wifi_pwd = server.arg("wifi_pwd");
    String api_key = server.arg("api_key");
    String ext1 = server.arg("ext1");
    String ext2 = server.arg("ext2");

    DEBUG_PRINTLN(debug, ( "================== Set Config ===================="));
    DEBUG_PRINTLN(debug, "设置 wifi_name：" + wifi_name);
    DEBUG_PRINTLN(debug, "设置 wifi_pwd：" + wifi_pwd);
    DEBUG_PRINTLN(debug, "设置 api_key：" + api_key);
    DEBUG_PRINTLN(debug, "设置 ext1：" + ext1);
    DEBUG_PRINTLN(debug, "设置 ext2：" + ext2);
    DEBUG_PRINTLN(debug, ("==================================================="));

    WiFi.begin(wifi_name, wifi_pwd);
    DEBUG_PRINT(debug, F("connect wifi ing.."));
    int connect_count = 0;
    // 10s 连不上Wifi的话就判定失败
    int try_count = 20;
    while (WiFi.status() != WL_CONNECTED && connect_count <= try_count)
    {
        connect_count++;
        delay(500);
        DEBUG_PRINT(debug, ".");
    }
    DEBUG_PRINTLN(debug, "");
    if (WiFi.status() != WL_CONNECTED)
    {
        DEBUG_PRINTLN(debug, ("设置 WIFI 连接失败"));
        ESP.restart();
        web_server_setCrossOrigin();
        String json_response = "{\"success\":false,\"message\":\"wifi连接失败，请检查账号密码\"}";
        server.send(200, "application/json", json_response);
        return;
    }

    set_local_data("wifi_name", wifi_name);
    set_local_data("wifi_pwd", wifi_pwd);
    set_local_data("api_key", api_key);
    set_local_data("ext1", ext1);
    set_local_data("ext2", ext2);

    web_server_setCrossOrigin();
    String json_response = "{\"success\":true,\"message\":\"设置成功, 即将重启设备。\"}";
    server.send(200, "application/json", json_response);

    // 重启板子
    delay(100);
    ESP.restart();
}

void ESP_AI::get_config()
{
    String loc_device_id = get_local_data("device_id");
    String loc_wifi_name = get_local_data("wifi_name");
    String loc_wifi_pwd = get_local_data("wifi_pwd");
    String loc_api_key = get_local_data("api_key");
    String loc_ext1 = get_local_data("ext1");
    String loc_ext2 = get_local_data("ext2");

    JSONVar json_response;
    JSONVar json_response_data;
    json_response["success"] = true;
    json_response_data["device_id"] = loc_device_id;
    json_response_data["wifi_name"] = loc_wifi_name;
    json_response_data["wifi_pwd"] = loc_wifi_pwd;
    json_response_data["api_key"] = loc_api_key;
    json_response_data["ext1"] = loc_ext1;
    json_response_data["ext2"] = loc_ext2;
    json_response["data"] = json_response_data;
    String send_data = JSON.stringify(json_response);

    web_server_setCrossOrigin();
    server.send(200, "application/json", send_data);
}

void ESP_AI::web_server_setCrossOrigin()
{
    server.sendHeader(F("Access-Control-Allow-Origin"), F("*"));
    server.sendHeader(F("Access-Control-Max-Age"), F("600"));
    server.sendHeader(F("Access-Control-Allow-Methods"), F("PUT,POST,GET,OPTIONS"));
    server.sendHeader(F("Access-Control-Allow-Headers"), F("*"));
};

void ESP_AI::web_server_init()
{ 
    server.on("/", [this]()
              { this->web_server_page_index(); });
    server.on("/set_config", [this]()
              { this->set_config(); });
    server.on("/get_config", [this]()
              { this->get_config(); });
    server.begin();
}

void ESP_AI::web_server_page_index()
{
    String content = "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><meta name='viewport'content='viewport-fit=cover,width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no'/><title>ESP-AI配网</title></head><body style='margin: 0;font-size: 16px; color: #333;height: 80vh;position: relative;font-family: 苹方,黑体;overflow: hidden;'><div style='height: 100%;display: flex;flex-direction: column; justify-content: center;align-items: center;'id='wifi_setting_panel'><div style='padding-bottom: 18px;text-align: center;'><img style='width:60px;'src=''/><div style='font-size: 22px;color: #757575;'>为ESP-AI设备配网</div></div><div style='width: 100%;padding: 8px 24px;box-sizing: border-box;'><input id='ssid'name='ssid'type='text'placeholder='请输入WIFI账号，仅支持2.4GHZ频段WIFI'style='border-radius: 3px;font-size:14px;padding: 12px 12px;box-sizing: border-box;border: 1px solid #cfcfcf;outline: none;width:100%;'></div><div style='width: 100%;padding: 8px 24px;box-sizing: border-box;'><input id='password'name='password'type='text'placeholder='请输入WIFI密码'style='border-radius: 3px;font-size:14px;padding: 12px 12px;box-sizing: border-box;border: 1px solid #cfcfcf;outline: none;width:100%;'></div><div style='width: 100%;padding: 8px 24px;box-sizing: border-box;'><input id='api_key'name='api_key'type='text'placeholder='请输入产品密钥, 请到开发者平台获取'style='border-radius: 3px;font-size:14px;padding: 12px 12px;box-sizing: border-box;border: 1px solid #cfcfcf;outline: none;width:100%;'></div><div style='width: 100%;text-align: right; padding: 6px 24px; padding-bottom: 32px; box-sizing: border-box;'><button id='submit-btn'style='width:100% ; box-sizing: border-box; border-radius: 3px; padding: 16px 0px;border: none;color: #fff;background-color: transparent; color:#fff; background: linear-gradient(45deg, #40cea5, #09aba2); box-shadow: 0px 0px 3px #ccc;letter-spacing: 2px;'>连接WIFI</button></div><div style='font-size: 13px;position: fixed;bottom: 12px;color:#929292'>设备编码：<span id='device_id'>-</span></div></div></body></html><script>var domain='';var loading=false;function myFetch(apiName,params,cb){fetch(domain+apiName,{mode:'cors'}).then(function(res){return res.json()}).then(function(data){cb&&cb(data)})};function refreshInfo(){myFetch('/get_config',{},function(res){console.log('wifi信息：',res);if(res.success){var data=res.data;document.querySelector('#ssid').value=data.wifi_name;document.querySelector('#password').value=data.wifi_pwd;document.querySelector('#api_key').value=data.api_key;document.querySelector('#device_id').innerHTML=data.device_id}else{alert('获取配置失败, 请刷新页面重试')}})};function setWifiInfo(){if(loading){return};var wifi_name=document.querySelector('#ssid').value;var wifi_pwd=document.querySelector('#password').value;var api_key=document.querySelector('#api_key').value;if(!wifi_name){alert('请输入 WIFI 账号哦~');return}if(!wifi_pwd){alert('请输入 WIFI 密码哦~');return}loading=true;document.querySelector('#submit-btn').innerHTML='配网中...';clearTimeout(window.reloadTimer);window.reloadTimer=setTimeout(function(){window.location.reload()},10000);myFetch('/set_config?wifi_name='+wifi_name+'&wifi_pwd='+wifi_pwd+'&api_key='+api_key,{},function(res){clearTimeout(window.reloadTimer);loading=false;document.querySelector('#submit-btn').innerHTML='连接WIFI';if(res.success){alert('配网成功，即将重启设备，关闭本页面即可');}else{alert('配网失败，请检查账号密码是否正确')}})};window.onload=function(){refreshInfo();document.querySelector('#submit-btn').addEventListener('click',setWifiInfo)}</script>";

    if(String(wifi_config.html_str) != ""){
        content = String(wifi_config.html_str);
    }
 
    web_server_setCrossOrigin(); // 避免跨域
    server.send(200, "text/html", content);
}